package com.lanou.web.controller;

import com.lanou.entity.Book;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 姚云鹏
 * Create at: 2018/6/22 14:51
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @ResponseBody
    @RequestMapping("/add")
    public Object add(Book book, @RequestParam("priImgFile") CommonsMultipartFile
            priImgFile, @RequestParam("subImgFiles") CommonsMultipartFile[]
                              subImgFiles, HttpServletRequest request) throws
            IOException {
        String priImgFileName = UUID.randomUUID().toString() + ".jpg";
        String priImg = "/static/img/" + priImgFileName;
        String priImgFileRealPath = request.getServletContext().getRealPath(priImg);
        IOUtils.copy(priImgFile.getInputStream(), new FileOutputStream
                (priImgFileRealPath));

        book.setPriImg(priImg);

        String subImgs = "";
        for (CommonsMultipartFile subImgFile : subImgFiles) {
            String subImgFileName = UUID.randomUUID().toString() + ".jpg";
            String subImg = "/static/img/" + subImgFileName;
            String subImgFileRealPath = request.getServletContext().getRealPath
                    (subImg);
            IOUtils.copy(subImgFile.getInputStream(), new FileOutputStream
                    (subImgFileRealPath));

            subImgs += subImg;
            subImgs += ",";
        }
        subImgs = subImgs.substring(0, subImgs.length() - 1);

        book.setSubImgs(subImgs);

        bookService.add(book);

        return null;
    }
}
